﻿using System;
using System.Web;
using System.Web.UI;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.IO;

namespace ASBCC.Utility
{
    public class UploadUtility
    {
          /// <summary>
        /// 保存上传的文件
        /// </summary>
        /// <param name="type">上传文件相关的业务类型</param>
        /// <param name="filename">文件名</param>
        /// <param name="server">HttpServerUtility</param>
        /// <param name="postedFile">HttpPostedFile</param>
        /// <param name="savedFilename">保存后的文件名</param>
        /// <param name="savedPath">保存后的路径</param>
        /// <param name="IsNeedProcessFileName">是否需要处理文件名：True-不需要对该文件名是否唯一得处理；False-需要对该文件名唯一处理</param>
        /// <returns>保存成功/失败</returns>
        public static bool SaveUploadFile(
            UploadFileType type,
            string filename,
            HttpServerUtility server,
            HttpPostedFile postedFile,
            ref string savedFilename,
            ref string savedPath,
            bool IsNeedProcessFileName,
            ref string oppositePath)
        {
            return SaveUploadSpecialFile(type, filename, server, postedFile, ref savedFilename, ref savedPath, IsNeedProcessFileName, ConfigUtility.UploadFolder, ref oppositePath);
        }
        /// <summary>
        /// 保存特殊上传的文件
        /// </summary>
        /// <param name="type">上传文件相关的业务类型</param>
        /// <param name="filename">文件名</param>
        /// <param name="server">HttpServerUtility</param>
        /// <param name="postedFile">HttpPostedFile</param>
        /// <param name="savedFilename">上传后的文件名</param>
        /// <param name="savedPath">上传后的路径</param>
        /// <param name="IsNeedProcessFileName">是否需要处理文件名：True-不需要对该文件名是否唯一得处理；False-需要对该文件名唯一处理</param>
        /// <param name="TypeDir">如果是临时文件：TypeDir="Temp"；临时文件：TypeDir="Temporary"；如果是下载文件：TypeDir="DownLoadFiles"，如果是摸板文件：TypeDir="Templet"</param>
        /// <param name="oppositePath">存放到数据表中的相对路径</param>
        /// <returns>保存成功/失败</returns>
        private static bool SaveUploadSpecialFile(
            UploadFileType type,
            string filename,
            HttpServerUtility server,
            HttpPostedFile postedFile,
            ref string savedFilename,
            ref string savedPath,
            bool IsNeedProcessFileName,
            string TypeDir,
            ref string oppositePath)
        {
            WindowsImpersonationContext context = NetworkImpersonateUser();   //本地调试暂时注释

            //step1:构造唯一文件名
            //savedFilename = "";
            string singletonFilename;

            if (IsNeedProcessFileName)
            {
                singletonFilename = MakeSingletonUploadFilename(filename);
            }
            else
            {
                singletonFilename = filename;
            }
            if (singletonFilename.Length == 0)
                return false;

            //step2:从配置文件中取得上传文件路径，由于该路径是跨服务器的，所以暂时不用server.MapPath
            //string dir = server.MapPath("~") + Configuration.UploadFolder;
            //if (TypeDir.Length > 0 && (!TypeDir.EndsWith(@"\") && !TypeDir.EndsWith(@"/")))
            //{
            //    TypeDir += @"\";
            //}

            string dir = String.Empty;
            if (ConfigUtility.UploadServerIP.Length > 0
                && (!ConfigUtility.UploadServerIP.EndsWith(@"\") && !ConfigUtility.UploadServerIP.EndsWith(@"/"))
                && (!TypeDir.StartsWith(@"\") && !TypeDir.StartsWith(@"/"))
                )
            {
                dir = ConfigUtility.UploadServerIP + @"\" + TypeDir;
            }
            else
            {
                dir = ConfigUtility.UploadServerIP + TypeDir;
            }

            oppositePath = "";

            //step3:创建最终存放文件的文件夹名称
            switch (type)
            {
                case UploadFileType.EZVisitDocument:
                    dir = ConfigUtility.UploadServerIP + ConfigUtility.EZVisitDocument;
                    break;
                default:
                    break;
            }

            //step4:建立“YYYYMM”的文件夹，目标是对文件按月份进行分类
            if (!TypeDir.Equals(ConfigUtility.TempletFolder))   //摸板文件由于数量较少，所以不要按月份分类
            {
                if (dir.EndsWith(@"\") || dir.EndsWith("/"))
                {
                    dir += DateTime.Now.ToString("yyyyMM");
                }
                else
                {
                    dir += @"\" + DateTime.Now.ToString("yyyyMM");
                }
            }

            oppositePath = dir.Replace(ConfigUtility.UploadServerIP, "");


            if (oppositePath.IndexOf(ConfigUtility.UploadFolder) >= 0)
            {
                oppositePath = oppositePath.Replace(ConfigUtility.UploadFolder, "");
            }

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            //step5:保存上传文件
            try
            {
                if (dir.EndsWith(@"\") || dir.EndsWith(@"/"))
                {
                    postedFile.SaveAs(dir + singletonFilename);
                }
                else
                {
                    postedFile.SaveAs(dir + @"\" + singletonFilename);
                }
            }
            catch
            {
                return false;
            }

            savedFilename = singletonFilename;
            savedPath = dir;

            context.Undo();   //本地调试暂时注释

            return true;

        }

        public enum UploadFileType
        {
            EZVisitDocument = 1,
            Other = -1
        }

        /// <summary>
        /// 构造唯一不重复文件名，以当前时间戳为文件名前部
        /// </summary>
        /// <param name="filename">原始文件名</param>
        /// <returns>构造后文件名</returns>
        public static string MakeSingletonUploadFilename(string filename)
        {
            if (filename.Trim().Length == 0)
                return "";

            string name = "";
            name = Path.GetFileName(filename);
            name = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fff_") + name;
            return name;
        }

        /// <summary>
        /// 登陆远程主机，用于文件上传
        /// </summary>
        /// <returns></returns>
        public static WindowsImpersonationContext NetworkImpersonateUser()
        {
            string strDomain = "";
            string strLogin = "";
            string strPwd = "";

            strDomain = ConfigUtility.FileServerDomain;
            strLogin = ConfigUtility.FileServerLogin;
            strPwd = ConfigUtility.FileServerPwd;

            //本地调式时，用：LOGON32_LOGON_NEW_CREDENTIALS
            WindowsImpersonationContext context = NetworkSecurity.ImpersonateUser(strDomain, strLogin, strPwd, LogonType.LOGON32_LOGON_INTERACTIVE, LogonProvider.LOGON32_PROVIDER_DEFAULT);
            // WindowsImpersonationContext context = NetworkSecurity.ImpersonateUser(strDomain, strLogin, strPwd, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_DEFAULT);

            return context;
        }

    }
}
